<?php
/**
 * Created by PhpStorm.
 * User: andrew
 * Date: 2015/8/30 0030
 * Time: 11:54
 */

namespace common\models;

use yii\base\Model;
use yii\behaviors\TimestampBehavior;
use yii\behaviors\BlameableBehavior;
use yii\db\Expression;
use yii\web\UploadedFile;
use yii\helpers\FileHelper;
use yii\web\IdentityInterface;

/**
 * UploadForm is the model behind the upload form.
 */
class UploadCoverForm extends Model
{
    /**
     * @var UploadedFile|Null file attribute
     */
    public $cover;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['cover'], 'file', 'extensions' => 'gif, jpg, png', 'maxSize' => 1024 * 1024 * 1, 'tooBig' => \Yii::t('app', 'File has to be smaller than 2MB')],
        ];
    }

    /**
     * fetch stored image file name with complete path
     * @return string
     */
    public function getImageFile()
    {
        return isset($this->cover) ? \Yii::$app->basePath .'/'. \Yii::$app->params['storagePath']. \Yii::$app->params['productBrandLogoDir'] . $this->logo : null;
    }

    /**
     * Process upload of image
     *
     * @return mixed the uploaded image instance
     */
    public function uploadImage()
    {
        // get the uploaded file instance. for multiple file uploads
        // the following data will return an array (you may need to use
        // getInstances method)
        $image = UploadedFile::getInstance($this, 'cover');

        // if no image was uploaded abort the upload
        if (empty($image)) {
            return false;
        }

        // generate a unique file name
        $this->cover = \Yii::$app->security->generateRandomString() . ".{$image->extension}";

        // the uploaded image instance
        return $image;
    }

    /**
     * Process deletion of image
     *
     * @return boolean the status of deletion
     */
    public function deleteImage($file)
    {

        // check if file exists on server
        if (empty($file)) {
            return false;
        }
        // 删除缓存的旧Logo
        $LogoCachePath = \Yii::$app->basePath .'/'. Yii::$app->params['storageCachePath']. Yii::$app->params['cmsCoverDir'];
        $files = glob("{$LogoCachePath}/*_{$file}");
        array_walk($files, function ($file) {
            unlink($file);
        });

        $LogoPath = \Yii::$app->basePath .'/'. Yii::$app->params['storagePath']. Yii::$app->params['cmsCoverDir'];
        $file = $LogoPath.$file;
        // check if uploaded file can be deleted on server
        if (!unlink($file)) {
            return false;
        }

        // if deletion successful, reset your file attributes
        //$this->logo = null;

        return true;
    }

    public function getBrandLogo($width = 50,$height=50)
    {
        if ($this->cover) {
            // TODO 写法更优雅
            $LogoPath = Yii::$app->basePath .'/'. Yii::$app->params['storagePath']. Yii::$app->params['cmsCoverDir'];
            $LogoCachePath = Yii::$app->basePath .'/'. Yii::$app->params['storageCachePath']. Yii::$app->params['cmsCoverDir'];
            FileHelper::createDirectory($LogoCachePath); // 创建文件夹
            if (file_exists($LogoCachePath. $width . '_' .$height .'_'. $this->logo)) {
                // 头像是否存在
                return Yii::$app->params['storageCacheUrl']. Yii::$app->params['cmsCoverDir'] . $width . '_' .$height .'_'. $this->logo;
            }
            \yii\imagine\Image::thumbnail($LogoPath . $this->cover, $width, $height)
                ->save($LogoCachePath. $width . '_' .$height .'_'. $this->logo, ['quality' => 100]);
            return Yii::$app->params['storageCacheUrl']. Yii::$app->params['cmsCoverDir'] . $width . '_' .$height .'_'. $this->logo;
        }
        return null;
    }

}